<?php
declare (strict_types = 1);
namespace app\api\logic;
use app\admin\model\UserCoupon;
use app\admin\model\mk\Coupon;
use app\admin\model\mk\Seckill;
use app\admin\model\mk\SeckillPro;
use app\common\service\MkService as mk_s;
use app\admin\model\mk\GamePrizeRecord as pr;
use app\admin\model\mk\Game;
use app\admin\model\mk\GamePrize as gp;
use app\admin\model\mk\Integral;
class MkLogic
{		
		// 用户优惠券列表
		function userCoupon($args = []){
				$type = $args['type'] ?? 'no_use';
				$w[] = ['user_id','=',$args['uid']];
				if($type == 0){
					$w[] = ['is_use','=',0];
					$w[] = ['end_time','>',time()]; 
				}
				if($type == 1){
					 $w[] = ['is_use','=',1];
				}
				if($type == 2){
					$w[] = ['is_use','=',0];
					$w[] = ['end_time','<=',time()]; 
					 
				}
				$res = UserCoupon::where($w)->select();
				foreach($res as &$v){
					  
				}
				return $res;
		}

		//秒杀活动

		function seckill($args = []){
			  $sid = $args['seckill_id'] ?? 0;
			  if($sid > 0){
			  	 
			  	   $res = Seckill::where(['shop_id'=>$args['shop_id'],'id'=>$sid])->find();
			  	   if(!$res){
			  	   	 return ['code'=>100,'back_type'=>1,'msg'=>'活动已下架'];
			  	   }
			  	   if($res['sdate'] < time()){
			  	   	  return ['code'=>100,'back_type'=>1,'msg'=>'活动未开始'];
			  	   }
			  	   if($res['edate'] < time()){
			  	   	  return ['code'=>100,'back_type'=>1,'msg'=>'活动已结束'];
			  	   }
			  	   $pro = SeckillPro::alias("s")->where(['s.seckill_id'=>$res['id'],'s.status'=>1])->join("goods p","p.id=s.pro_id","LEFT")->field("s.*,p.feng,p.title,p.price")->order("s.sort desc")->select();
			  	   foreach($pro as &$v){
			  	   		$v['progress'] = floor($v['sell_num']/$v['seckill_stock']);  //进度
			  	   }
			  	   $data = [
			  	   		'seckill'=>$res,
			  	   		'seckill_pro'=>$pro??[]
			  	   ];
			  	   return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>$data];
			  }else{
			  	   return ['code'=>100,'back_type'=>1,'msg'=>'活动已结束'];
			  }
		}
		// 大转盘抽奖
		function wheel($args = []){
				$id = $args['id'] ?? 0;
				if($id){
					$res = Game::where(['shop_id'=>$args['shop_id'],'id'=>$id,'status'=>1,'type'=>'wheel'])->find();
					if(!$res){
						 return ['code'=>100,'back_type'=>1,'msg'=>'Lost Actives'];
					}
					$res['stime'] = date("Y-m-d H:i",$res['stime']);
					$res['etime'] = date("Y-m-d H:i",$res['etime']);
					$prize = gp::where("guan_id",$res['id'])->order("sort desc")->select();
					$res['prize'] = $prize;

					foreach($prize as &$v){
						 $p = [
							 	'fonts' => [
						            ['text' => $v['title'], 'top' => '10%', 'fontSize' => '12px', 'fontColor' => '#B43002']
						        ],
						        'background' => '#FFED8C',
						        'imgs' => [
						            ['src' => $v['pic'], 'width' => '20', 'top' => '22']
						        ]
						 ];
						 $prizes[] = $p;
					}
					$res['jsonData'] = json_encode($prizes ?? []);
				 
					return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>$res];
				}else{
					return ['code'=>100,'back_type'=>1,'msg'=>'Lost Actives'];
				}
		}
		// 大转盘抽取奖品
		function getWheelPrize($args = []){
			$id = $args['id'] ?? 0;
			if($id){
				$res = Game::where(['shop_id'=>$args['shop_id'],'id'=>$id,'status'=>1,'type'=>'wheel'])->find();
				if(!$res){
					return ['code'=>100,'back_type'=>1,'msg'=>'Lost Actives'];
				}
				
				if($res['limit_type'] == 0){
					$yichou = pr::where(['user_id'=>$args['uid'],'game_id'=>$res['id']])->count();
					if($yichou >= $res['limit_num']){
						 return ['code'=>100,'back_type'=>1,'msg'=>'机会已用完'];
					}
					
				}
				if($res['limit_type'] == 1){
					$yichou = pr::where(['user_id'=>$args['uid'],'game_id'=>$res['id']])
					->whereTime('time', '>=', date('Y-m-d', time()))
                    ->whereTime('time', '<', date('Y-m-d', time() + 86400))
					->count();
					if($yichou >= $res['limit_num']){
						 return ['code'=>100,'back_type'=>1,'msg'=>'今日机会已用完'];
					}
				}

				$arr = [];
                $xiexie = [];
				$pro = gp::where("guan_id",$res['id'])->order("sort desc")->select();
				foreach($pro as $k2=>$val){
					$arr[$k2]['id']       = $k2;
                    $arr[$k2]['name']     = $val['title'];
                    $arr[$k2]['v']        = $val['probability'];
                    $arr[$k2]['prize_id'] = $val['id'];
                    $arr[$k2]['pic']      = $val['pic'];
                    $arr[$k2]['dex']      = $val['prize_dex'];
                    if($val['no_prize'] == 1){
                          $xiexie =  $arr[$k2];
                    }
				}
				$prize = get_rand($arr);
                $this_num = gp::where("id",$prize['prize_id'])->value("stock");
                if($this_num <=0){  //奖品库存为0  则直接显示谢谢参与
                    $prize = $xiexie;
                }
                if(empty($prize)){
					return ['code'=>100,'back_type'=>1,'msg'=>'操作异常'];
                }
            	//生成抽奖记录
                $r             = array();
                $r['user_id']      = $args['uid'];
                $r['prize_title']    = $prize['name'];
                $r['pic']      = $prize['pic'];
                $r['time']     = time();
                $r['game_id']  = $res['id'];
                $r['prize_id'] = $prize['prize_id'];
                $r['shop_id'] = $args['shop_id'];
                $rid           = pr::insertGetId($r);
                if(!$rid) {
                   return ['code'=>100,'back_type'=>1,'msg'=>'服务异常'];
                }
                gp::where("id",$prize['prize_id'])->setDec("stock");
				return ['code'=>200,'back_type'=>1,'msg'=>'ok','data'=>['rid'=>$rid,'prize'=>$r]];
			}else{
				return ['code'=>100,'back_type'=>1,'msg'=>'Lost Actives'];
			}	
		}
		//奖品领取
		function prizeLing($args = []){
			 $rid = $args['rid'] ?? 0;
			 if($rid){
			 	  $data = pr::alias("p")->join("mk_game_prize z","p.prize_id=z.id","LEFT")->field("z.type,z.money,z.jifen,z.quan,z.pro_id,p.status,p.user_id,p.shop_id")->where(['p.shop_id'=>$args['shop_id'],'p.id'=>$rid])->find();

			 	  if(!$data){
			 	  	  return ['code'=>100,'back_type'=>1,'msg'=>'无效操作!'];
			 	  }else{
			 	  	  if($data['status']>0){
			 	  	  	 return ['code'=>100,'back_type'=>1,'msg'=>'请勿重复领取'];
			 	  	  }
			 	  	  $up = pr::where(['shop_id'=>$args['shop_id'],'id'=>$rid])->update(['status'=>1,'ling_time'=>time()]);
			 	  	  if($up){
			 	  	  	   $ms = new mk_s();
			 	  	  	   $ms->getPrize($data);
			 	  	  	   return ['code'=>200,'back_type'=>1,'msg'=>'ok'];
			 	  	  }else{
			 	  	  	   return ['code'=>100,'back_type'=>1,'msg'=>'领取失败'];
			 	  	  }
			 	  }
			 }else{
			 	  return ['code'=>100,'back_type'=>1,'msg'=>'无效操作'];
			 }	
		}

		//领取优惠券

		function quanLing($args = []){
			 $id = $args['id'] ?? 0;
			 $quan = Coupon::where(['id'=>$id,'shop_id'=>$args['shop_id']])->find();
			 if($quan){
			 	if($quan['status'] == 1 && $quan['stock'] > 0){

			 		 $find = UserCoupon::where(['user_id'=>$args['uid'],'coupon_id'=>$quan['id']])->find();
			 		 if($find){
			 		 	 return ['code'=>100,'back_type'=>1,'msg'=>'请勿重复领取'];  
			 		 }
			 		 if($quan['time_type'] == 1){
			 		 		$end_time = strtotime($quan['end_time']);
			 		 }
			 		 if($quan['time_type'] == 2){
			 		 		$end_time = $quan['end_day']*24*3600 + time();
			 		 }
			 		 $addID = UserCoupon::insert([
			 		 		'title'=>$quan['title'],
			 		 		'mian_money'=>$quan['mian_money'],
			 		 		'require_money'=>$quan['require_money'],
			 		 		'require_type'=>$quan['require_type'],
			 		 		'des'=>$quan['des'],
			 		 		'goods_id'=>$quan['goods_id'],
			 		 		'details'=>$quan['detais'],
			 		 		'coupon_id'=>$quan['id'],
			 		 		'ling_time'=>time(),
			 		 		'user_id'=>$args['uid'],
			 		 		'end_time'=>$end_time ?? '',
			 		 		'time_type'=>$quan['time_type']

			 		 ]);

			 		 if($addID){
			 		 	 Coupon::where(['id'=>$id,'shop_id'=>$args['shop_id']])->setInc("ling_num");
			 		 	 return ['code'=>200,'back_type'=>1,'msg'=>'ok'];  
			 		 }else{
			 		 	 return ['code'=>100,'back_type'=>1,'msg'=>'领取失败，请重试！'];  
			 		 }
			 	}else{
			 	     return ['code'=>100,'back_type'=>1,'msg'=>'来晚一步，已抢光'];  
			 	}
			 }else{
			 	return ['code'=>100,'back_type'=>1,'msg'=>'券已下架'];  
			 }

		}

		//积分商城
		function integralShop($args = []){
			$w[] = ['s.shop_id','=',$args['shop_id']];
			$w[] = ['s.status','=',1];
			$data = Integral::alias("s")->join("goods g","s.pid=g.id","LEFT")->field("s.*,g.title,g.feng")->where($w)->order("sort desc")->select();
			return $data;
		}

}